package com.momoauth.common.security.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.momoauth.common.security.config.SecurityConfig;
import org.springframework.util.DigestUtils;

import java.util.Date;

public interface SecurityAdapter {

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    Long login(String username, String password);

    /**
     * MD5密码
     * @param password
     * @param salt
     * @return
     */
    default String getMD5Pwd(String password, String salt) {
        String base = password + salt;
        return DigestUtils.md5DigestAsHex(base.getBytes());
    }

    /**
     * 判断密码是否一致
     * @param pwd1
     * @param pwd2
     * @return
     */
    default boolean verify(String pwd1, String pwd2) {
        if (pwd1 != null && pwd2 != null) {
            return pwd1.equals(pwd2);
        }
        return false;
    }

    /**
     * 创建令牌
     * @param username
     * @param userId
     * @return
     */
    default String createToken(String username, Long userId) {
        Date date = new Date(System.currentTimeMillis() + SecurityConfig.expire_time);
        Algorithm algorithm = Algorithm.HMAC256(SecurityConfig.secret);
        return JWT.create()
                .withClaim("username", username)
                .withClaim("userId", String.valueOf(userId))
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 解析载荷信息
     * @param token
     * @param name
     * @return
     */
    default String getClaimName(String token, String name) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(name).asString();
    }
}
